﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace Calico.Server.Filters
{
	/// <summary>
	/// Authorize Attribute for identifying Authorized Users
	/// </summary>
	public class AuthorizedUserAttribute : AuthorizeAttribute
	{
		/// <summary>
		/// Called when a controller or action is being authorized.
		/// </summary>
		/// <remarks>
		/// Override checks the current user against the custom user
		/// </remarks>
		/// <param name="context"></param>
		/// <returns>bool</returns>
		protected override bool IsAuthorized(HttpActionContext httpActionContext)
		{
			//// Vars
			//AppsManager appsManager = new AppsManager(SqlHelper.ConnectionString("PPB.Apps"));

			//// Is Authorized
			//string appName = WebConfigHelper.GetAppSetting("PPB.AppName");
			//Guid appAuthID = CastValue.AsGuid(GetAuthorizationHeader(httpActionContext));
			//bool isAuthorized = appsManager.IsAuthorized(appName, appAuthID);

			//// Exit if not authorized
			//if (!isAuthorized) return false;

			// Success
			return true;
		}

		/// <summary>
		/// Handles an unauthorized user
		/// </summary>
		/// <remarks>
		/// Override creates a custom HttpResponseMessage
		/// </remarks>
		/// <param name="context"></param>
		protected override void HandleUnauthorizedRequest(HttpActionContext httpActionContext)
		{
			HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Forbidden);
			httpActionContext.Response = message;
		}

		private string GetAuthorizationHeader(HttpActionContext httpActionContext)
		{
			string result = String.Empty;

			try
			{
				result = httpActionContext.Request.Headers.Authorization.ToString();
			}
			catch { }

			return result;
		}
	}
}